package com.bao.auth.server.demo.monster;

import java.math.BigDecimal;
import java.util.PriorityQueue;

public class Hero {
    public static void main(String[] args) {
        //int[] maxHP = {1, 4, 3, 5, 3, 2, 8, 6, 4, 3, 8, 3, 8, 2, 18, 16, 14, 3, 8, 13, 8};
        //int[] maxHP = {1, 1, 1,1, 5};
        int[] maxHP = {1, 6};
        /**
         * 3,4
         * 3
         */
        Hero hero = new Hero();
        int num = hero.attack(maxHP);
        System.out.println("攻击次数：--》" + num);
    }

    public int attack(int[] maxHP){
        PriorityQueue<Monster> minHeap = addHeap(maxHP);
        int num = 0;
        //循环攻击血量最低敌人
        while (!minHeap.isEmpty()) {
            //攻击血量最少敌人
            Monster m = minHeap.poll();
            int currentHp = m.current_HP - 1;
            if(currentHp > 0){
                m.setCurrent_HP(currentHp);
               num += ishalf(m,minHeap);
            }
            num ++;
        }
        
        return num;
    }
    


    /**
     * 血量是否到一半了
     */
    public int ishalf(Monster monster,PriorityQueue<Monster> minHeap){
        int maxHp = monster.max_HP;
        int currentHp = monster.current_HP;
        int num = 0;
        BigDecimal two = new BigDecimal(2);
        BigDecimal halh = new BigDecimal(maxHp).divide(two, BigDecimal.ROUND_HALF_DOWN);
        //当前被攻击者血量低于50，全体攻击一次
        if (halh.floatValue() > currentHp){
            allAttack(minHeap,num);
        }else {
            minHeap.add(monster);
        }
        return num;
    }

    public void allAttack(PriorityQueue<Monster> minHeap,int num){
        PriorityQueue<Monster> newHeap = new PriorityQueue<>(((o1, o2) -> o1.max_HP - o2.max_HP));
        //当次攻击，是否有野怪血量降低到了一半一下
        boolean isHalf = false;
        BigDecimal two = new BigDecimal(2);
        
        while (!minHeap.isEmpty()){
            Monster poll = minHeap.poll();
            int maxHp = poll.max_HP;
            int currentHp = poll.current_HP - 1;
            num ++;
            if (currentHp > 0){
                BigDecimal halh = new BigDecimal(maxHp).divide(two, BigDecimal.ROUND_HALF_DOWN);
                if (halh.floatValue() > currentHp){
                    isHalf = true;
                }
                newHeap.add(new Monster(maxHp,currentHp));
            }
        }
        minHeap = newHeap;
        if (isHalf){
            allAttack(newHeap,num);
        }
    }
    
    public PriorityQueue<Monster> addHeap(int[] maxHP){
        PriorityQueue<Monster> minHeap = new PriorityQueue<>(((o1, o2) -> o1.max_HP - o2.max_HP));
        if (maxHP == null || maxHP.length == 0){
            return null;
        }
        //所有怪物加入小根堆，初始血量和最大血量为传入血量
        for (int i = 0; i < maxHP.length; i ++){
            if(maxHP[i] > 0){
                minHeap.add(new Monster(maxHP[i],maxHP[i]));
            }
        }
        return minHeap;
    }
}
